<template>
  <div class="chat-container">
    <a-layout>
      <a-layout-sider width="250" style="background: #fff">
        <div class="sidebar-header">
          <h3>面试记录</h3>
          <a-button type="primary" @click="startNewInterview">开启新面试</a-button>
        </div>
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="inline"
          @click="handleMenuClick"
        >
          <a-menu-item v-for="room in chatRooms.value" :key="room.id">
            {{ room.title }}
          </a-menu-item>
        </a-menu>
      </a-layout-sider>

      <a-layout-content class="chat-content">
        <!-- 新增输入格式提示 -->
        <div class="input-format-hint">
          面试开始，这里是Java面试，请开始自我介绍，首次输入必须要包含以下这两个词：<strong>岗位</strong>（包括初级/中级/高级），<strong>技术栈</strong>
        </div>
        <div v-if="currentRoomId" class="chat-area">
          <div class="messages-container">
            <div v-for="(message, index) in messages.value" :key="index" class="message-wrapper">
              <ChatMessage :message="message" />
            </div>
          </div>

          <div class="input-area">
            <a-button
              danger
              :disabled="isInterviewEnded"
              @click="endInterview"
              class="end-button"
              :loading="isEnding"
            >
              <template #icon v-if="isEnding">
                <LoadingOutlined />
              </template>
              {{ isEnding ? '结束中...' : '结束' }}
            </a-button>
            <a-input-group compact>
              <a-input
                v-model:value="inputMessage"
                placeholder="输入消息..."
                @pressEnter="sendMessage"
                :disabled="isInterviewEnded"
              />
              <a-button
                type="primary"
                @click="sendMessage"
                :disabled="isInterviewEnded || isSending"
                :loading="isSending"
              >
                <template #icon v-if="isSending">
                  <LoadingOutlined />
                </template>
                {{ isSending ? '发送中...' : '发送' }}
              </a-button>
            </a-input-group>
          </div>
        </div>

        <div v-else class="empty-state">
          <a-empty description="请选择或创建一个新的面试房间" />
        </div>
      </a-layout-content>
    </a-layout>
  </div>

  <!-- 添加全局加载提示 -->
  <a-spin :spinning="isSending" tip="AI面试官正在思考..." size="large" />
  <a-spin :spinning="isEnding" tip="正在结束面试..." size="large" />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useChatStore } from '@/stores/chatStore'
import ChatMessage from '@/components/ChatMessage.vue'

const chatStore = useChatStore()
const inputMessage = ref('')
const selectedKeys = ref([])
const isInterviewEnded = ref(false)
const currentRoomId = ref(null);
const isSending = ref(false) // 新增发送状态
const isEnding = ref(false) // 新增结束状态

const { chatRooms,  messages, fetchChatRooms, createChatRoom, sendChatMessage, loadChatMessages } = chatStore

onMounted(async () => {
  try {
    // 调用action并等待返回结果
    const rooms = await fetchChatRooms()
    chatRooms.value = rooms // 将结果赋值给本地ref
    if (chatRooms.value.length > 0) {
      selectedKeys.value = [chatRooms.value[0].id]
      const messageList = await loadChatMessages(chatRooms.value[0].id)
      messages.value = messageList;
      currentRoomId.value = rooms[0].id
    }
  } catch (error) {
    message.error('加载聊天记录失败')
  }
})

const startNewInterview = async () => {
  try {
    currentRoomId.value = await createChatRoom()
    const rooms = await fetchChatRooms()
    chatRooms.value = rooms // 将结果赋值给本地ref
    selectedKeys.value = [currentRoomId.value]
    const messageList = await loadChatMessages(currentRoomId.value)
    messages.value = messageList;
    isInterviewEnded.value = false
  } catch (error) {
    console.log(error)
    message.error('创建新面试失败')
  }
}

const handleMenuClick = async ({ key }) => {
  try {
    const messageList = await loadChatMessages(key)
    currentRoomId.value = key
    messages.value = messageList;
    checkInterviewEnded()
  } catch (error) {
    console.log(error)
    message.error('加载聊天记录失败')
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || !chatStore.currentRoomId || isSending.value) {
    return
  }
  try {
    if (!inputMessage.value.trim() || !chatStore.currentRoomId || isSending.value) {
      return
    }
    isSending.value = true
    await sendChatMessage(currentRoomId.value, inputMessage.value)
    inputMessage.value = ''
    checkInterviewEnded()
  } catch (error) {
    console.log(error)
    message.error(error)
  } finally {
    isSending.value = false
  }
}

const endInterview = async () => {
  try {
    if (!chatStore.currentRoomId || isEnding.value) {
      return
    }
    isEnding.value = true
    await sendChatMessage(currentRoomId.value, '面试结束')
    isInterviewEnded.value = true
  } catch (error) {
    message.error('结束面试失败')
  } finally {
    isEnding.value = false
  }
}

const checkInterviewEnded = () => {
  if (messages.value.length > 0) {
    const lastMessage = messages.value[messages.value.length - 1]
    isInterviewEnded.value = lastMessage.content.includes('面试已结束')
  }
}

watch(messages.value, checkInterviewEnded, { deep: true })
</script>

<style scoped>
.chat-container {
  height: 100vh;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  text-align: center;
}

.chat-content {
  padding: 24px;
  background: #fff;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 新增输入格式提示样式 */
.input-format-hint {
  position: sticky;
  top: 0;
  background: #fff;
  padding: 12px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
  z-index: 1;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.input-format-hint strong {
  color: #1890ff;
  font-weight: normal;
}

.chat-area {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.message-wrapper {
  margin-bottom: 16px;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.ant-spin {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/* 为结束按钮添加自定义样式 */
.end-button {
  margin-right: 10px;
  background-color: #ff4d4f; /* 红色背景 */
  border-color: #ff4d4f; /* 红色边框 */
  color: white; /* 白色文字 */
}

/* 禁用状态下的样式 */
.end-button[disabled] {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: rgba(0, 0, 0, 0.25);
}

/* 悬停效果 */
.end-button:not([disabled]):hover {
  background-color: #ff7875;
  border-color: #ff7875;
}
</style>
